<?php


namespace app\api\controller\User;


use app\api\controller\AppController;
use app\api\model\Order\OrderGoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\User\UserLevelModel;
use app\Request;
use app\Utils\CalculateUtil;
use app\Utils\StrUtil;
use app\Utils\Util;
use app\Utils\WechatPayUtil;
use Exception;
use think\facade\Db;

class UserVip extends AppController
{
    /**
     * @api {post} /create_user_vip_order 创建VIP会员订单
     * @apiGroup 用户
     * @apiParam {string} token Token
     * @apiParam {int} id 等级ID
     * @apiParam {int} source_type 来源 1:APP 2:微信公众号 3:小程序
     * @apiParam {int} pay_way 支付方式 1：余额  2:支付宝 3：微信
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function createUserVipOrder(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        //1:APP 2:微信公众号 3:小程序
        if (!in_array($param['source_type'], [1, 2, 3])) {
            return Util::returnJson(self::CODE_ERROR, null, "来源错误");
        }
        if (!in_array($param['pay_way'], [1, 2, 3])) {
            return Util::returnJson(self::CODE_ERROR, null, "支付类型错误");
        }
        $level = UserLevelModel::getUserLevelWhere(['id' => $param['id']]);
        if (!$level) {
            return Util::returnJson(self::CODE_ERROR, null, "当前等级信息不存在或已下架");
        }
        //验证会员是否永久
        if (!empty($user['is_level_type'])) {
            return Util::returnJson(self::CODE_ERROR, null, "你已经是永久会员了");
        }
        //商户订单号
        $out_trade_no = StrUtil::i()->getOrderSn(3);
        //VIP订单号
        $order_sn = StrUtil::i()->getOrderSn();
        $data = [
            'uid' => $user['id'],
            'order_sn' => $order_sn,
            'type' => 2,
            'total_price' => $level['price'],
            'price' => $level['price'],
            'deduction_price' => 0,
            'pay_way' => $param['pay_way'],
            'source_type' => $param['source_type'],
            'pay_num' => 1,
            'is_discounts' => 0,
            'is_group' => 0,
            'status' => 0,
            'up_time' => date('Y-m-d H:i:s', time()),
            'add_time' => date('Y-m-d H:i:s', time())
        ];
        $total_price = $level['price'];
        Db::startTrans();
        try {
            $order_id = OrderModel::addOrder($data);
            if ($order_id) {
                $order_goods_data = [
                    'order_id' => $order_id,
                    'type' => 2,
                    'goods_id' => $param['id'],
                    'goods_info' => json_encode($level),
                    'number' => 1,
                    'total_price' => $level['price'],
                    'goods_price' => $level['price'],
                    'is_sales' => $level['is_sales'],
                    'up_time' => date("Y-m-d H:i:s", time()),
                    'add_time' => date("Y-m-d H:i:s", time())
                ];
                //--------开始分销计算--------
                $order_goods_data = CalculateUtil::i()->commissionCalculate($user, $level, $total_price, $order_goods_data);
                //添加订单商品
                $flag = OrderGoodsModel::addOrderGoods($order_goods_data);
                if (!$flag) {
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR, null, "订单创建失败");
                }
                //--------结束分销计算--------
                $result1 = null;
                $result = null;
                //支付
                if ($param['pay_way'] == 1) {
                    //余额支付
                } else if ($param['pay_way'] == 2) {
                    $order_save = [
                        'out_trade_no' => $out_trade_no
                    ];
                    OrderModel::updateOrderWhere([['id', '=', $order_id]], $order_save);
                    //支付宝支付
                    $result = $this->aliPay($data['total_price'], $out_trade_no, "购买会员");
                } else if ($param['pay_way'] == 3) {
                    //微信支付
                    $order_save = [
                        'out_trade_no' => $out_trade_no
                    ];
                    OrderModel::updateOrderWhere([['id', '=', $order_id]], $order_save);
                    $wx = new WechatPayUtil();
                    $result1 = $wx->wechat_pay($out_trade_no, $data['total_price'], '购买VIP支付');
                }

                if ($result['code'] == 0) {
                    $data = [
                        'pay_way' => $param['pay_way'],
                        'pay_info' => $result ? $result['data'] : '',
                        'wx_pay' => $result1
                    ];
                    Db::commit();
                    return Util::returnJson(self::CODE_SUCCESS, $data, "下单成功");
                } else {
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR, null, $result['msg']);
                }
            } else {
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR, null, "订单创建失败");
            }
        } catch (Exception $e) {
            Db::rollback();
            var_dump($e);
            return Util::returnJson(self::CODE_ERROR, null, "系统错误");
        }
    }

}